import axios from 'axios';

// 获取当前API基础URL
const getAPIBaseURL = () => {
  const port = 8080; // 默认端口
  return `http://localhost:${port}/api`; // 添加/api前缀
};

// Create an axios instance with default config
const API = axios.create({
  baseURL: getAPIBaseURL(),
  headers: {
    'Content-Type': 'application/json',
  },
  timeout: 10000, // 10秒
  withCredentials: true, // 允许跨域携带cookie
});

// 开启请求调试
API.interceptors.request.use(
  config => {
    console.log('Request:', config.method.toUpperCase(), config.url);
    console.log('Request Data:', config.data);
    return config;
  },
  error => {
    return Promise.reject(error);
  }
);

// Add a request interceptor to add auth token to requests
API.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem('token');
    if (token) {
      config.headers['Authorization'] = `Bearer ${token}`;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// Add a response interceptor to handle common errors
API.interceptors.response.use(
  (response) => {
    console.log('Response:', response.status, response.data);
    return response;
  },
  (error) => {
    console.error('API Error:', error.response?.status, error.response?.data || error.message);
    if (error.response) {
      if (error.response.status === 401) {
        localStorage.removeItem('token');
        localStorage.removeItem('userInfo');
        window.location.href = '/login';
      }
    } else if (error.request) {
      console.error('No response received:', error.request);
      console.log('请检查后端服务是否运行在端口8080上');
    } else {
      console.error('Request error:', error.message);
    }
    return Promise.reject(error);
  }
);

// 直接注册api，使用fetch作为后备
export const registerDirectly = async (userData) => {
  try {
    console.log('尝试使用fetch直接注册:', userData);
    const response = await fetch(`${getAPIBaseURL()}/auth/register`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(userData),
    });
    
    const data = await response.json();
    console.log('Direct register response:', data);
    return data;
  } catch (error) {
    console.error('Direct register error:', error);
    throw error;
  }
};

// Auth Services
export const authService = {
  register: (userData) => {
    console.log('Sending registration data:', userData);
    return API.post('/auth/register', userData);
  },
  login: (credentials) => {
    console.log('Sending login data:', credentials);
    return API.post('/auth/login', credentials);
  },
  logout: () => {
    localStorage.removeItem('token');
    localStorage.removeItem('userInfo');
    return Promise.resolve();
  },
  getCurrentUser: () => API.get('/auth/current'),
  saveUserInfo: (userInfo) => {
    localStorage.setItem('userInfo', JSON.stringify(userInfo));
  },
  getUserInfo: () => {
    const userInfo = localStorage.getItem('userInfo');
    return userInfo ? JSON.parse(userInfo) : null;
  }
};

// Movies Services
export const movieService = {
  getAllMovies: () => API.get('/movies'),
  getMovieById: (id) => API.get(`/movies/${id}`),
  getScreeningsByMovieId: (id) => API.get(`/movies/${id}/screenings`),
  getReviewsByMovieId: (id) => API.get(`/movies/${id}/reviews`),
  addReview: (movieId, reviewData) => API.post(`/movies/${movieId}/reviews`, reviewData),
};

// Booking Services
export const bookingService = {
  createBooking: (bookingData) => API.post('/bookings', bookingData),
  getUserBookings: () => API.get('/bookings/me'),
  getBookingById: (id) => API.get(`/bookings/${id}`),
  cancelBooking: (id) => API.put(`/bookings/${id}/cancel`),
};

export default API; 